package com.yami.shop.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderCloseResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yami.shop.bean.app.param.PayInfoParam;
import com.yami.shop.bean.bo.PayInfoBo;
import com.yami.shop.bean.bo.RefundInfoBo;
import com.yami.shop.bean.enums.BackType;
import com.yami.shop.bean.event.BalancePayEvent;
import com.yami.shop.bean.event.BalanceRefundEvent;
import com.yami.shop.bean.model.OrderSettlement;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.common.bean.Domain;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.config.AliPayConfig;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.service.PayManagerService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 统一支付工具
 *
 * @author LGH
 */
@Service
@AllArgsConstructor
public class PayManagerServiceImpl implements PayManagerService {

    private AliPayConfig aliPayConfig;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ShopConfig shopConfig;

    private WxConfig wxConfig;

    private final ApplicationContext applicationContext;

    private static final String WX_SUCCESS_XML = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private static final String ALI_SUCCESS = "success";

    @Override
    public ResponseEntity<?> doPay(HttpServletResponse httpResponse, PayInfoDto payInfo) throws WxPayException, IOException, AlipayApiException {

        if (payInfo.getPayAmount() < 0.01 && payInfo.getIsScore() == 1) {
            return ResponseEntity.ok().build();
        }

        //微信支付不能大于1000w
        if (payInfo.getPayAmount() < 0.01 || payInfo.getPayAmount() > 10000000.00) {
            // 订单金额有误，无法进行支付
            throw new YamiShopBindException("yami.order.amount.error");
        }
        String domainName = shopConfig.getDomain().getApiDomainName();
        // 如果是商家端需要回调，则使用商家端的地址
        if(Objects.nonNull(payInfo.getBackType()) && Objects.equals(payInfo.getBackType(), BackType.SHOP.value())){
            domainName = shopConfig.getDomain().getMultishopDomainName();
        }
        String notifyUrl = domainName + payInfo.getApiNoticeUrl();

        PayType payType = PayType.instance(payInfo.getPayType());
        if (isWxPay(payType)) {

            WxPayService wxPayService = wxConfig.getWxPayService(payType);
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody(payInfo.getBody());
            orderRequest.setOutTradeNo(payInfo.getPayNo());
            orderRequest.setTotalFee((int) Arith.mul(payInfo.getPayAmount(), 100));
            orderRequest.setSpbillCreateIp(IPHelper.getIpAddr());
            orderRequest.setOpenid(payInfo.getBizUserId());

            orderRequest.setNotifyUrl(notifyUrl);

            // 微信小程序支付
            if (Objects.equals(payType, PayType.WECHATPAY)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
                WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMpOrderResult);
            }
            // 微信网页支付
            else if (Objects.equals(payType, PayType.WECHATPAY_SWEEP_CODE)) {
                orderRequest.setProductId(payInfo.getPayNo());
                // 生成微信二维码
                orderRequest.setTradeType(WxPayConstants.TradeType.NATIVE);
                WxPayNativeOrderResult wxPayNativeOrderResult = wxPayService.createOrder(orderRequest);

                return ResponseEntity.ok(wxPayNativeOrderResult.getCodeUrl());
            }
            // 微信H5支付
            else if (Objects.equals(payType, PayType.WECHATPAY_H5)) {
                // 生成微信二维码
                orderRequest.setTradeType(WxPayConstants.TradeType.MWEB);
                String s = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"\",\"wap_name\": \"\"}}";
                orderRequest.setSceneInfo(s);
                WxPayMwebOrderResult wxPayMwebOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMwebOrderResult.getMwebUrl());
            }
            // 微信公众号支付
            else if (Objects.equals(payType, PayType.WECHATPAY_MP)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
                WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMpOrderResult);
            }
            // 微信app支付
            else if (Objects.equals(payType, PayType.WECHATPAY_APP)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.APP);
                WxPayAppOrderResult wxPayAppOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayAppOrderResult);
            }
        } else if (Objects.equals(payType, PayType.ALIPAY)) {
            //创建API对应的request
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            //在公共参数中设置回跳和通知地址
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());
            AlipayTradePagePayModel alipayTradePagePayModel = new AlipayTradePagePayModel();
            alipayTradePagePayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradePagePayModel.setBody(payInfo.getBody());
            alipayTradePagePayModel.setSubject(payInfo.getBody());
            alipayTradePagePayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradePagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY");
            alipayRequest.setBizModel(alipayTradePagePayModel);

            return ResponseEntity.ok(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        } else if (Objects.equals(payType, PayType.ALIPAY_H5)) {

            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());

            AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
            alipayTradeWapPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeWapPayModel.setSubject(payInfo.getBody());
            alipayTradeWapPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeWapPayModel.setProductCode("QUICK_WAP_PAY");
            alipayRequest.setBizModel(alipayTradeWapPayModel);
            return ResponseEntity.ok(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        }
        // 支付宝app支付
        else if (Objects.equals(payType, PayType.ALIPAY_APP)) {

            AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            AlipayTradeAppPayModel alipayTradeAppPayModel = new AlipayTradeAppPayModel();
            alipayTradeAppPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeAppPayModel.setSubject(payInfo.getBody());
            alipayTradeAppPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeAppPayModel.setProductCode("QUICK_MSECURITY_PAY");
            alipayRequest.setBizModel(alipayTradeAppPayModel);

            String body = aliPayConfig.getAlipayClient().sdkExecute(alipayRequest).getBody();
            return ResponseEntity.ok(body);
        }
        //余额支付
        else if (Objects.equals(payType, PayType.BALANCE)){
            PayInfoParam payInfoParam = new PayInfoParam();
            applicationContext.publishEvent(new BalancePayEvent(payInfo,payInfoParam));
            return ResponseEntity.ok(payInfoParam);
        }
        return null;
    }

    @Override
    public PayInfoBo validateAndGetPayInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        PayInfoBo payInfoBo = new PayInfoBo();
        // 小程序支付
        if (isWxPay(payType)) {
            WxPayService wxPayService = wxConfig.getWxPayService(payType);
            WxPayOrderNotifyResult parseOrderNotifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            payInfoBo.setPayNo(parseOrderNotifyResult.getOutTradeNo());
            payInfoBo.setBizPayNo(parseOrderNotifyResult.getTransactionId());
            payInfoBo.setIsPaySuccess(true);
            payInfoBo.setSuccessString(WX_SUCCESS_XML);

        } else if (isAliPay(payType)) {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = parseAliNotifyAndGetResult(request);

            if (Objects.equals(params.get("trade_status"), "TRADE_SUCCESS")) {
                //商户订单号,之前生成的带用户ID的订单号
                payInfoBo.setPayNo(params.get("out_trade_no"));
                //支付宝交易号
                payInfoBo.setBizPayNo(params.get("trade_no"));
                payInfoBo.setIsPaySuccess(true);
                payInfoBo.setSuccessString(ALI_SUCCESS);
            } else {
                payInfoBo.setIsPaySuccess(false);
            }
        }
        return payInfoBo;
    }

    @Override
    public PayInfoBo getPayInfo(PayType payType, String payNo) {
        PayInfoBo payInfo = new PayInfoBo();
        payInfo.setPayNo(payNo);

        try {
            if (isWxPay(payType)) {
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                WxPayOrderQueryResult wxPayOrderQueryResult = wxPayService.queryOrder(null, payNo);
                if (!Objects.isNull(wxPayOrderQueryResult) && Objects.equals(wxPayOrderQueryResult.getTradeState(), Constant.SUCCESS)) {
                    payInfo.setBizPayNo(wxPayOrderQueryResult.getTransactionId());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else if (isAliPay(payType)) {
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
                alipayTradeQueryModel.setOutTradeNo(payNo);

                request.setBizModel(alipayTradeQueryModel);
                AlipayTradeQueryResponse response = aliPayConfig.getAlipayClient().execute(request);
                if (response.isSuccess()) {
                    payInfo.setBizPayNo(response.getTradeNo());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else {
                payInfo.setIsPaySuccess(false);
            }
        } catch (WxPayException | AlipayApiException e) {
            e.printStackTrace();
            payInfo.setIsPaySuccess(false);
        }
        return payInfo;
    }

    @Override
    public boolean doRefund(RefundInfoDto refundInfo) {

        PayType payType = refundInfo.getPayType();
        if(refundInfo.getRefundAmount() == 0){
            return true;
        }
        Domain domain = shopConfig.getDomain();
        // 提交提款操作
        try {
            if (isWxPay(payType)) {
                // 退款操作
                // 生成退款请求对象
                WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
                // 商户订单号
                wxPayRefundRequest.setOutTradeNo(refundInfo.getPayNo());
                // 订单金额
                double totalFee = Arith.mul(refundInfo.getPayAmount(), 100);
                wxPayRefundRequest.setTotalFee((int) totalFee);
                // 退款金额
                double refundFee = Arith.mul(refundInfo.getRefundAmount(), 100);
                wxPayRefundRequest.setRefundFee((int) refundFee);
                // 退款编码
                wxPayRefundRequest.setOutRefundNo(refundInfo.getRefundSn());


                // notifyUrl（通知结果）
                wxPayRefundRequest.setNotifyUrl(domain.getMultishopDomainName() + refundInfo.getNotifyUrl());
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                wxPayService.refund(wxPayRefundRequest);

            } else if (isAliPay(payType)) {
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                request.setNotifyUrl(domain.getMultishopDomainName() + refundInfo.getNotifyUrl());
                AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
                alipayTradeRefundModel.setOutTradeNo(refundInfo.getPayNo());
                alipayTradeRefundModel.setRefundAmount(Double.toString(refundInfo.getRefundAmount()));
                alipayTradeRefundModel.setOutRequestNo(refundInfo.getRefundSn());
                request.setBizModel(alipayTradeRefundModel);
                AlipayTradeRefundResponse response = aliPayConfig.getAlipayClient().certificateExecute(request);
                // 对fund_change必须了解为本次退款操作，若相同退款参数调用，第一次返回fund_change=Y，第二次返回fund_change=N，但是第二次仍返回退款信息。
                if (BooleanUtil.toBoolean(response.getFundChange())) {
                    return true;
                }
            }else if (Objects.equals(payType, PayType.BALANCE)){
                applicationContext.publishEvent(new BalanceRefundEvent(refundInfo));
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new YamiShopBindException(e.getCustomErrorMsg(), e);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new YamiShopBindException(e.getErrMsg(), e);
        }
        return false;
    }

    @Override
    public Boolean cancelOrderQrCode(List<OrderSettlement> orderSettlements) throws WxPayException,AlipayApiException {
        Map<Integer, String> payTypeMap = orderSettlements.stream().collect(Collectors.toMap(OrderSettlement::getPayType, OrderSettlement::getPayNo));
        for (Integer payType : payTypeMap.keySet()) {
            PayType type = PayType.instance(payType);
            if (isWxPay(type)) {
                WxPayService wxPayService = wxConfig.getWxPayService(type);
                wxPayService.closeOrder(payTypeMap.get(payType));
                return true;
            }else{
                AlipayTradeCloseRequest tradeCloseRequest = new AlipayTradeCloseRequest();
                AlipayTradeCloseModel tradeCloseModel = new AlipayTradeCloseModel();
                tradeCloseModel.setOutTradeNo(payTypeMap.get(payType));
                tradeCloseRequest.setBizModel(tradeCloseModel);
                AlipayTradeCloseResponse response = aliPayConfig.getAlipayClient().execute(tradeCloseRequest);
                logger.warn(response.getBody());
                if(response.isSuccess()){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public RefundInfoBo validateAndGetRefundInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        RefundInfoBo refundInfoBo = new RefundInfoBo();
        refundInfoBo.setIsRefundSuccess(false);

        if (isWxPay(payType)) {
            WxPayRefundNotifyResult wxPayRefundNotifyResult = wxConfig.getWxPayService(payType).parseRefundNotifyResult(xmlData);
            WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
            //
            if ("SUCCESS".equals(reqInfo.getRefundStatus())) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setSuccessString(WX_SUCCESS_XML);
                refundInfoBo.setRefundNo(reqInfo.getOutRefundNo());
                refundInfoBo.setBizRefundNo(reqInfo.getRefundId());
            }
        } else if (isAliPay(payType)) {
            Map<String, String> params = parseAliNotifyAndGetResult(request);
            if (Objects.equals(params.get("trade_status"), "TRADE_SUCCESS") || Objects.equals(params.get("trade_status"), "TRADE_CLOSED")) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setRefundNo(params.get("out_biz_no"));
                refundInfoBo.setBizRefundNo("");
                refundInfoBo.setSuccessString(ALI_SUCCESS);
            }
        }


        return refundInfoBo;
    }

    //获取支付宝POST过来反馈信息
    private Map<String, String> parseAliNotifyAndGetResult(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //乱码解决，这段代码在出现乱码时使用
        request.setCharacterEncoding("utf-8");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCertCheckV1(params, shopConfig.getAlipay().getAlipayCertPath(), cn.hutool.core.util.CharsetUtil.UTF_8, AlipayConstants.SIGN_TYPE_RSA2);

        if (!signVerified) {
            // 验签失败
            throw new YamiShopBindException("yami.sign.check");
        }
        return params;
    }


    private boolean isWxPay(PayType payType) {
        return (Objects.equals(payType, PayType.WECHATPAY)
                || Objects.equals(payType, PayType.WECHATPAY_SWEEP_CODE)
                || Objects.equals(payType, PayType.WECHATPAY_H5)
                || Objects.equals(payType, PayType.WECHATPAY_MP)
                || Objects.equals(payType, PayType.WECHATPAY_APP));
    }

    private boolean isAliPay(PayType payType) {
        return (Objects.equals(payType, PayType.ALIPAY_H5)
                || Objects.equals(payType, PayType.ALIPAY)
                || Objects.equals(payType, PayType.ALIPAY_APP));
    }
}
